package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_GENERAL_RISK_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER', 'ROLE_BRANCH_OFFICE_RISK_MANAGER', 'ROLE_HEAD_OFFICE_RISK_MANAGER', 'ROLE_GENERAL_MANAGER', 'ROLE_CRO', 'ROLE_CEO', 'ROLE_POST_LOAN_MANAGER', 'ROLE_BRANCH_OFFICE_POST_LOAN_MANAGER'])
@Transactional(readOnly = true)
class HouseController
{
    def mailService
    def propertyValuationProviderService
    def springSecurityService
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        respond House.list(params), model: [collateralCount: House.count()]
    }

    def show(House house)
    {
        def photoes = Attachments.findAllByOpportunityAndType(house?.opportunity, AttachmentType.findByName("估值附回材料"))
        respond house, model: [photoes: photoes]
    }

    def create()
    {
        respond new House(params)
    }

    @Transactional
    def save(House house)
    {
        if (house == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (house.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond house.errors, view: 'create'
            return
        }
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        house.createdBy = user
        house.modifiedBy = user

        house.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'house.label', default: 'house'), house.id])
                // redirect house
                redirect(controller: "opportunity", action: "show", params: [id: house?.opportunity?.id])
            }
            '*' { respond house, [status: CREATED] }
        }
    }

    def edit(House house)
    {
        respond house
    }

    @Transactional
    def update(House house)
    {
        if (house == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (house.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond house.errors, view: 'edit'
            return
        }
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        house.modifiedBy = user

        house.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'house.label', default: 'house'), house.id])
                // redirect house
                redirect(controller: "opportunity", action: "show", params: [id: house?.opportunity?.id])
            }
            '*' { respond house, [status: OK] }
        }
    }

    @Transactional
    def ajaxUpdate(House house)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        house.modifiedBy = user
        /*house.firstMortgageAmount = house.firstMortgageAmount * 10000
        house.secondMortgageAmount = house.secondMortgageAmount * 10000*/
        if (house.validate())
        {
            house.save flush: true
            render([status: "success"] as JSON)
            return
        }
        else
        {
            render([status: "fail", errorMessage: house.errors] as JSON)
            return
        }
    }

    @Transactional
    def delete(House house)
    {

        if (house == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        house.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'house.label', default: 'house'), house.id])
                // redirect action: "index", method: "GET"
                redirect(controller: "opportunity", action: "show", params: [id: house?.opportunity?.id])
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'house.label', default: 'house'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    @Transactional
    def recoveryCollateral()
    {
        def opportunity = Opportunity.findById(params['opportunity'])
        def house
        if (opportunity?.houses?.size() <= 0 && opportunity?.city)
        {
            house = new House()
            if (opportunity?.assetType?.name)
            {
                house.assetType = opportunity?.assetType?.name
            }

            house.city = opportunity?.city
            house.floor = opportunity?.floor
            house.orientation = opportunity?.orientation
            house.area = opportunity?.area
            house.totalFloor = opportunity?.totalFloor
            house.roomNumber = opportunity?.roomNumber
            house.houseType = opportunity?.houseType?.name
            house.specialFactors = opportunity?.specialFactors
            house.unitPrice = opportunity?.unitPrice
            house.totalPrice = opportunity?.loanAmount
            house.status = 'Completed'
            house.opportunity = opportunity
            house?.building = 0
            house.unit = 0
            if (opportunity?.district)
            {
                house.projectName = opportunity?.district
                house.district = opportunity?.district
            }
            else if (opportunity?.address)
            {
                house.projectName = opportunity?.address
                house.district = opportunity?.address
            }

            if (opportunity?.address)
            {
                house.address = opportunity?.address
            }
            else if (opportunity?.district)
            {
                house.address = opportunity?.district
            }

            if (house.validate())
            {
                house.save flush: true
            }
            else
            {
                println house.errors
            }
        }
        redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
    }

    def queryValuationReliability(House house)
    {
        def externalId = params["externalId"]
        def pvCollateral = [:]
        if (externalId)
        {
            def pvJson = propertyValuationProviderService.queryByExternalId(externalId)
            if (pvJson)
            {
                def valuationReliability = pvJson['valuationReliability']
                def unitPrice = pvJson['unitPrice']
                pvCollateral['valuationReliability'] = valuationReliability
                pvCollateral['unitPrice'] = unitPrice
            }
            else
            {
                pvCollateral['valuationReliability'] = ""
                pvCollateral['unitPrice'] = 0
            }
        }
        else
        {
            pvCollateral['valuationReliability'] = ""
            pvCollateral['unitPrice'] = 0
        }
        render([status: "success", pvCollateral: pvCollateral] as JSON)
    }

    @Secured('permitAll')
    @Transactional
    def queryByExternalId()
    {
        def id = params['externalId']
        id = String.valueOf(id)
        def house = House.findByExternalId(id)
        println house
        def opportunity = house?.opportunity
        def serialNumber = opportunity?.serialNumber
        def json = [:]
        if (opportunity)
        {
            json['serialNumber'] = serialNumber

        }
        else
        {
            println "22"
        }
        render json as JSON
    }

    def modifyCollateralInformation(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def applyReasonAndContent = params.applyReasonAndContent
        def house = opportunity?.houses.getAt(0)
        // if (applyReasonAndContent && house)
        // {
        //     try
        //     {
        //         mailService.sendMail {
        //             to "<qutingting@cindata.com>"
        //             // cc  "<caoxiuran@126.com>"
        //             from "<qls@cindata.com>" //"昵称<邮箱>"
        //             subject "修改房产信息申请"
        //             html "<p>曲婷婷：</p>" + "<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您好！麻烦修改一下以下问题。</p>" + "<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + applyReasonAndContent + "</p>" + "<p>房产ID为:" + house?.externalId + "</p>" + "<p>订单号为:" + opportunity?.serialNumber + "</p>" + "<p>借款人为:" + opportunity?.fullName + "</p>" + "<p style='text-algin:right'>申请人：" + user?.fullName + "</p>"
        //         }
        //         println "邮件发送成功"
        //     }
        //     catch (Exception e)
        //     {
        //         e.printStackTrace()
        //         println("邮件发送失败，错误信息：<br/>" + e.getMessage())
        //     }
        // }
        redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
    }

    @Transactional
    def searchCollateral()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0

        def max = params.max
        def offset = params.offset

        String sql = "from House as o where 1 = 1"
        def projectName = params["projectName"]
        if (projectName)
        {
            sql += " and o.projectName like '%${projectName}%'"
        }

        def externalId = params["externalId"]
        if (externalId)
        {
            sql += " and o.externalId = '${externalId}'"
        }

        def serialNumber = params["serialNumber"]
        if (serialNumber)
        {
            sql += " and o.opportunity.serialNumber = '${serialNumber}'"
        }

        def startTime = params["startTime"]
        def endTime = params["endTime"]
        if (startTime && endTime)
        {
            sql += " and o.createdDate between '${startTime}' and '${endTime}'"
        }

        def city = params["city"]
        if (city && city != "null")
        {
            sql += " and o.city.name = '${city}'"
        }

        sql += " order by o.createdDate desc"
        println sql
        def list = House.findAll(sql, [max: max, offset: offset])
        def list1 = House.findAll(sql)
        Integer count = list1.size()

        respond list, model: [collateralCount: count, params: params], view: 'index'
    }

    @Transactional
    def searchOldOpportunityNumbers()
    {
        def oid = params.opportunityId
        if (oid)
        {
            def map = [:]
            def map1
            def list = []
            def oids = []
            def size = 0
            def house = House.findByOpportunity(Opportunity.findById(oid))
            def oldCollaterals = House.findAllByPropertySerialNumberAndOpportunityNotEqual(house?.propertySerialNumber, house?.opportunity)
            oldCollaterals.each {
                def opportunity = it?.opportunity
                if (opportunity?.isTest != true && opportunity?.status != "Failed" && opportunity?.createdDate?.format("yyyy-MM-dd") > "2017-04-01")
                {
                    //                    if (OpportunityFlow.findByOpportunityAndStage(opportunity, OpportunityStage.findByName("基础材料已提供"))?.endTime)
                    //                    {
                    //
                    //                    }
                    oids.add(opportunity?.id)
                }
            }
            if (oids.size() > 0)
            {
                def opportunitys = Opportunity.findAllByIdInList(oids)
                opportunitys.each {
                    map1 = [:]
                    map1["serialNumber"] = it?.serialNumber
                    map1["fullName"] = it?.fullName
                    list.add(map1)
                }
                size = opportunitys?.size()
            }
            map["size"] = size
            map["list"] = list
            render map as JSON
        }
    }
}
